# -*- coding:utf-8 -*-
from utils.views import AuthenticationExceptView, WdCreateAPIView, WdListCreateAPIView, WdRetrieveUpdateAPIView, \
    WdDestroyAPIView, WdListAPIView, WdAPIView
from utils.response import general_json_response, ErrorCode
from rest_framework import status
from users.models import AuthUser, CompanyInfo, CompanyWebsiteInfo, Person, Registry, PersonPositions
from django.contrib.auth.hashers import make_password
from utils.logger import get_logger
from serializer import AppAuthUserSerializer, CompanySerializer, CompanyListSerializer, PersonSerializer, \
    PersonListSerializer, CompanyListSerializerV2, AppPersonSerializer, AppPersonListSerializer, \
    AppPropertyAuthUserSerializer
from django.contrib.auth import login, authenticate, logout
from version.version import versions
import json
import operator
from basic.models import ElevatorInfo
import datetime
import random
from haversine import haversine


logger = get_logger(__name__)


class AppLoginView(AuthenticationExceptView, WdCreateAPIView):
    u"""用户登录接口
    """
    model = AuthUser
    serializer_class = AppAuthUserSerializer

    def post(self, request, *args, **kwargs):
        username = request.data.get('username', None)
        pwd = request.data.get("pwd", None)
        if username is None or pwd is None:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)
        user = authenticate(username=username, password=pwd)
        if not user:
            return general_json_response(status.HTTP_200_OK, ErrorCode.USER_PWD_ERROR)
        if user.role in [0, 20]:
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)
        login(request, user)
        s = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now()) + ''.join([str(random.randint(1, 10)) for i in range(5)])
        user.session = s
        user.save()
        request.session['session'] = s
        user_info = AppAuthUserSerializer(instance=user, many=False).data
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, user_info)


class AppLogoutView(WdCreateAPIView):
    u"""Web登出"""
    def post(self, request, *args, **kwargs):
        try:
            logout(request)
        except Exception, e:
            logger.error("web logout error, msg(%s)" % e)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class AppPersonDetailView(WdRetrieveUpdateAPIView):

    model = Person
    p_serializer_class = AppPersonSerializer
    serializer_class = AppPersonListSerializer
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True

    def post_check_parameter(self, kwargs):
        code = super(AppPersonDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        phone = self.request.data.pop('phone', None)
        image = self.request.data.pop('image', None)
        pwd = self.request.data.pop('pwd', None)
        old_pwd = self.request.data.pop('old_pwd', None)
        sign_image = self.request.data.pop('sign_image', None)
        person = self.get_object()
        user = person.auth_user
        print "auth_user is %s " % user
        if phone:
            user.phone = phone
            user.save()
        if image:
            user.image = image
            user.save()
        if sign_image:
            user.sign_image = sign_image
            user.save()

        if pwd and old_pwd:
            user = authenticate(username=user.username, password=old_pwd)
            if not user:
                return ErrorCode.USER_PWD_ERROR
            else:
                password = make_password(pwd)
                user.password = password
                user.save()
        return code


class AppPropertyDetailView(WdRetrieveUpdateAPIView):

    model = AuthUser
    serializer_class = AppPropertyAuthUserSerializer
    POST_DATA_RESPONSE = True
    POST_DATA_ID_RESPONSE = True

    def post_check_parameter(self, kwargs):
        code = super(AppPropertyDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        pwd = self.request.data.pop('pwd', None)
        old_pwd = self.request.data.pop('old_pwd', None)
        user = self.get_object()
        if pwd and old_pwd:
            user = authenticate(username=user.username, password=old_pwd)
            if not user:
                return ErrorCode.USER_PWD_ERROR
            else:
                password = make_password(pwd)
                self.request.data['password'] = password
        return code


class APPRegistryQueryView(WdAPIView):

    def get(self, request):
        task_id = self.request.GET.get('task_id', None)
        task_type = self.request.GET.get('task_type', None)
        if not task_type or not task_type:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, u'参数不正确，请核实')
        register = Registry.objects.filter(type_for_reg='Task', reg_obj_id=task_id, task_type=task_type).last()
        if register:
            msg = register.msg
        else:
            msg = u'未查到备案信息'
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, msg)


class AppVersionControlView(WdAPIView):

    def get(self, request):
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, versions)


class AppPersonPositionView(WdCreateAPIView):

    def post(self, request, *args, **kwargs):
        user = self.request.user
        person = user.person
        service_id = user.person.service_id
        update_by = user.id
        position = self.request.data.get('position', None)
        logger.info("记录位置信息")
        logger.info(user.real_name)
        if position:
            logger.info(position)
            pp = PersonPositions.objects.filter(person=person).order_by('-id').first()
            if not pp:
                PersonPositions.objects.create(person=person, service_id=service_id, update_by=update_by,
                                               position=position)
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)
            position_now = tuple(sorted([float(i) for i in position.split(",")]))
            position_pre = tuple(sorted([float(i) for i in pp.position.split(",")]))
            distance = haversine(position_now, position_pre)
            # if distance >= 0.3:
            if distance >= 0.05:
                PersonPositions.objects.create(person=person, service_id=service_id, update_by=update_by,
                                               position=position)
                pp.is_new = False
                pp.save()
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)
        logger.info("位置信息为空")
        return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"缺少参数position")






